package com.iticit.util;

import cfca.sadk.cgb.toolkit.BASE64Toolkit;
import cfca.sadk.cgb.toolkit.SM4Toolkit;

public class SM4Utils {
	public static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp;
		for (int i = 0; i < b.length; i++) {
			stmp = Integer.toHexString(b[i] & 0xFF).toUpperCase();
			if (stmp.length() == 1) {
				hs.append("0").append(stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString();
	}

	/**
	 * 使用国密SM4加密字符串
	 *
	 * @param key
	 * @param data
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String SM4EncryptData(String key, String data, String encoding) throws Exception {
		String result = null;
		try {
			SM4Toolkit toolkit = new SM4Toolkit();
			toolkit.SM4Init(key.getBytes(), key.getBytes());
			byte[] enByte = toolkit.SM4EncryptData(data.getBytes(encoding));
			result = BASE64Toolkit.encode(enByte);
		} catch (Exception e) {
			throw e;
		}
		return result;
	}
	
	/**
	 * 使用国密SM4解密字符串
	 * @param key
	 * @param data
	 * @param encoding
	 * @return
	 * @throws Exception 
	 */
	public static String SM4DecryptData(String key,String data,String encoding) throws Exception{
		String result=null;
		try{
			SM4Toolkit toolkit=new SM4Toolkit();
			toolkit.SM4Init(key.getBytes(), key.getBytes());
			byte[]  enByte=toolkit.SM4DecryptData(BASE64Toolkit.decode(data));
			result= new String(enByte,encoding);
		}catch(Exception e){
			throw e;
		}
		return result;
	}
}
